%EEGLAB already loaded

%change this:
load ('d:\temp\essai_class_s5_A.mat');

%asuming every event generates one peoch 

if ( length(EEG.epoch) ~= length(EEG.event) )
   error('Event count diffrs from epoch count!')
end;
    
%X = EEG.data(:,129:256,:);
X = EEG.data([1:2:64],1:256,:);
%input = EEG.data([1:4:64],1:256,:);
% 
% %M1 = sum(input,3) ./size(input,3);
% M = mean(input,3);
% 
% X = zeros(2*size(input,1),size(input,2),size(input,3));
% 
% for i = 1: size(input,3)
%     X(:,:,i) = [input(:,:,i); M;];
% end;

Y = [EEG.event.type]';

Fs = EEG.srate;

%% Classification over X and Y

% covariance estimation
COV = covariances(X);

%shuffuling
NTrial = size(X,3); % trials equals movements
disp(['NTrials: ' int2str(NTrial)]);
ix = randperm(NTrial);

% permutate the data for classification
COV = COV(:,:,ix); % the sequence is updated from 1 ... ntrial to a random permutation
Ys = Y(ix); % it takes Y in the permutated form

% cross validation
NCV = 10;
% MDM
disp('---------- MDM --------------');
%out = cross_valid(COV,Ys,NCV,@mdm,'riemann','ld'); % COV is produced from X and Ys is produced from Y
out = cross_valid(COV,Ys,NCV,@mdm); % COV is produced from X and Ys is produced from Y
disp('Confusion matrix :');
disp(confusionmat(Ys,out));
disp(['Accuracy : ' num2str(100*mean(Ys==out)) ' %']);


% FGMDM
disp('---------- FGMDM --------------');
out = cross_valid(COV,Ys,NCV,@fgmdm);
disp('Confusion matrix :');
disp(confusionmat(Ys,out));
disp(['Accuracy : ' num2str(100*mean(Ys==out)) ' %']);

% K-NN
disp('---------- KNN --------------');
% 10 neigbourg
out = cross_valid(COV,Ys,NCV,@knn,10);
disp('Confusion matrix :');
disp(confusionmat(Ys,out));
disp(['Accuracy : ' num2str(100*mean(Ys==out)) ' %']);

% LDA on std
disp('---------- LDA on std (no Riemannian geometry) --------------');
Feat = sqrt(squeeze(sum(X(:,:,ix).^2,2)))';
%  Constants
NTrial = size(X,3);
NTrialTest = fix(NTrial/NCV);
out = zeros(size(X,3),1);
%cross validation
for iCV = 1:NCV 

    idxTest = 1+(iCV-1)*NTrialTest:iCV*NTrialTest;
    if iCV ==NCV
        idxTest = 1+(iCV-1)*NTrialTest:NTrial;
    end
    idxTraining = 1:NTrial;
    idxTraining(idxTest)=[];

    out(idxTest) = classify(Feat(idxTest,:),Feat(idxTraining,:),Ys(idxTraining));

end
disp('Confusion matrix :');
disp(confusionmat(Ys,out));
disp(['Accuracy : ' num2str(100*mean(Ys==out)) ' %']);